package com.example.util;


import com.example.filter.TpMonitorFilter;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;

/**
 * @author kangshuai
 */
public class ReportStatus implements Runnable {
    /**
     * 90分位
     */
    protected double percent90 = 0.9;
    /**
     * 99分位
     */
    protected double percent99 = 0.99;

    /**
     * 遍历存储的HashMap
     * 对每个方法调用的时间TreeSet 进行处理
     */
    @Override
    public void run() {
        System.out.println("开始上报...");
        HashMap<String, TreeSet<TpMonitorFilter.Dimension>> statistics = TpMonitorFilter.REQUEST_STATISTICS;

        //遍历hashmap
        Set<Map.Entry<String, TreeSet<TpMonitorFilter.Dimension>>> set = statistics.entrySet();
        for (Map.Entry<String, TreeSet<TpMonitorFilter.Dimension>> entry : set) {
            String service = entry.getKey();
            TreeSet<TpMonitorFilter.Dimension> value = entry.getValue();
            report(value, service);
        }
        System.out.println("==================================");
    }

    /**
     * 获取一分钟前时间
     * 存储数据中的结束时间小于一分钟前时间，删除一分钟数据
     * 计算分位点
     * 输出相应分位点时间
     *
     * @param statistics
     * @param service
     */
    protected void report(TreeSet<TpMonitorFilter.Dimension> statistics, String service) {
        synchronized (statistics) {
            //获取一分钟前的时间
            long startTime = System.currentTimeMillis() - 60 * 1000;
            for (TpMonitorFilter.Dimension data : statistics) {
                if (data.sendTime < startTime) {
                    statistics.remove(data);
                }
            }

            int size = statistics.size();
            int percent90Point = (int) (size * percent90);
            int percent99Point = (int) (size * percent99);

            TpMonitorFilter.Dimension percent90PointData = null;
            TpMonitorFilter.Dimension percent99PointData = null;
            int counter = 1;
            for (TpMonitorFilter.Dimension data : statistics) {
                if (counter == percent90Point) {
                    percent90PointData = data;
                } else if (counter == percent99Point) {
                    percent99PointData = data;
                }
                counter++;
            }

            System.out.println("服务【" + service + "】最近一分钟运行结果：");
            System.out.println("  90分位点耗时：" + percent90PointData.spendTime);
            System.out.println("  99分位点耗时：" + percent99PointData.spendTime);
        }
    }
}
